﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ParameterViewModel.cs" company="R.V.Kasner">
//   Copyright © 2011 R.V.Kasner
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Owen.Terminal.ViewModel
{
    using System;
    using System.Globalization;

    using GalaSoft.MvvmLight;

    using Owen.Terminal.Commons;

    public class ParameterViewModel : ViewModelBase
    {
        private readonly Parameter parameter;

        private static readonly string FloatFormat;

        private bool isReadable;

        static ParameterViewModel()
        {
            FloatFormat = "F" + Properties.Settings.Default.FloatAccuracy;
        }

        public ParameterViewModel(Parameter parameter)
        {
            this.parameter = parameter;
            this.isReadable = true;
        }

        public event Action<ParameterViewModel> FavoriteChanged;

        public bool IsFavorite
        {
            get
            {
                return this.parameter.IsFavorite;
            }

            set
            {
                this.parameter.IsFavorite = value;
                this.RaisePropertyChanged("IsFavorite");
                this.RaiseFavoriteChanged();
            }
        }

        public Parameter Parameter
        {
            get
            {
                return this.parameter;
            }
        }

        public string Value
        {
            get
            {
                if (this.parameter.ParamType == ParameterTypes.Float)
                {
                    return ((float)this.parameter.Value).ToString(FloatFormat, CultureInfo.CreateSpecificCulture("en-US"));
                }

                return this.parameter.Value.ToString();
            }

            set
            {
                try
                {
                    this.parameter.Value = Parameter.ConvertToNativeValue(value, this.parameter.ParamType);
                }
                catch
                {
                }

                this.RaisePropertyChanged("Value");
            }
        }

        public bool IsReadable
        {
            get
            {
                return this.isReadable;
            }

            set
            {
                if (this.isReadable == value)
                {
                    return;
                }

                this.isReadable = value;
                this.RaisePropertyChanged("IsReadable");
            }
        }

        private void RaiseFavoriteChanged()
        {
            var handler = this.FavoriteChanged;
            if (handler != null)
            {
                handler(this);
            }
        }
    }
}